const { talentPolicyDetail } = require('../../../../api/index');
const { replaceImg } = require('../../../../utils/util');
const { talentPolicyCollect, talentPolicyCancelCollect, checkCollect } = require('../../../api/collect');

// pages/active/detail3/index.js
Page({
  data: {
    id: '',
    content: '',
    isCollcet: false,
    detail: {},
    formData: {}
  },
  async onLoad(options) {
    this.data.id = options.id;
    await fetchTalentPolicyDetail.call(this);
    setFormData.call(this);
    await initCollect.call(this);
  },
  async onCollect() {
    //  点击 检查是否收藏过
    const res = await fetchCheckCollect.call(this);

    if(res) { //  说明收藏了
      await fetchPopularActivityCancelCollect.call(this);
    } else { // 说明未收藏
      await fetchPopularActivityCollect.call(this);
    }
  },
  onShareAppMessage() {

  }
})

//  请求 富文本
async function fetchTalentPolicyDetail() {
  const { errors = [], talentPolicy } = await talentPolicyDetail({ id: this.data.id });
  if( errors.length > 0 ) { return; }
  this.setData({ detail: setTalentPolicy( talentPolicy ) });
}

//  处理富文本数据
function setTalentPolicy( data ) {
  const _data = JSON.parse(JSON.stringify(data));

  _data.policyContent = replaceImg(_data.policyContent);

  return _data;
}

//  处理请求数据
async function setFormData() {
  this.data.formData.targetId = this.data.id; 
  this.data.formData.title = this.data.detail.title;
  this.data.formData.realName = wx.getStorageSync('userInfo')?.realName;
}

async function initCollect() {
  const res = await fetchCheckCollect.call(this);
  res ? this.setData({ isCollcet: true }) : this.setData({ isCollcet: false });
}

// 检查 是否被收藏
async function fetchCheckCollect(data) {
  const {
    errors = [],
    result,
  } = await checkCollect(this.data.formData);
  if (errors.length > 0) {
    return;
  }
  console.log(result)
  return result === '1'; //  判断是否收藏
}

//  收藏
async function fetchPopularActivityCollect(data) {
  const {
    errors = [],
    collect = false
  } = await talentPolicyCollect(this.data.formData);
  if (errors.length > 0) {
    myToast('收藏失败', 'error');
    return;
  }
  this.setData({ isCollcet: true });
  myToast('收藏成功', 'success');
}

//  取消收藏
async function fetchPopularActivityCancelCollect(data) {
  const {
    errors = [],
    result,
    collect = false
  } = await talentPolicyCancelCollect(this.data.formData);
  if (errors.length > 0) {
    myToast('取消收藏失败', 'error');
    return;
  }

  //  改变图标的颜色
  this.setData({ isCollcet: false });

  myToast('取消收藏成功', 'success');

}

//  弹窗封装
function myToast(title, icon, duration = 1000) {
  wx.showToast({
    title,
    icon,
    duration
  });
}